package com.bihua.shop.service;

import java.util.Map;

import org.springframework.stereotype.Service;

import com.bihua.common.utils.StringUtils;
import com.bihua.system.domain.SysConfig;
import com.bihua.system.service.ISysConfigService;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ：enilu
 * @date ：Created in 1/19/2020 4:31 PM
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class WeixinService {

    private final ISysConfigService configService;

    public void updateWeixinToken() {
        String accessToken = getAccessToken();
        String jsapiTicket = getJsapiTicket(accessToken);
        //weixin.access.token
        SysConfig tokenCfg = configService.selectConfigById(1704811946427625474L);
        tokenCfg.setConfigValue(accessToken);
        configService.updateConfig(tokenCfg);
        //weixin.js.api.ticket
        SysConfig tidCfg = configService.selectConfigById(1704811816387424257L);
        tidCfg.setConfigValue(jsapiTicket);
        configService.updateConfig(tidCfg);
    }

    public String getAccessToken() {
        String appId = configService.selectConfigByKey("weixin.app.id");
        String appSecret = configService.selectConfigByKey("weixin.app.secret");
        String accessTokenUrl = configService.selectConfigByKey("weixin.access.token.url");
        String url = String.format(accessTokenUrl, appId, appSecret);
        String result = HttpUtil.get(url);
        log.info("获取微信token，\r\nurl : {},\r\n result : {}", url, result);
        JSONObject object = JSONUtil.parseObj(result);
        String access_token = (String)object.get("access_token");
        return access_token;
    }

    public String getJsapiTicket(String accessToken) {
        String jsapiTicketUrl = configService.selectConfigByKey("weixin.js.api.ticket.url");
        String url = String.format(jsapiTicketUrl, accessToken);
        String result = HttpUtil.get(url);
        log.info("获取微信Ticket，\r\nurl : {},\r\n result : {}", url, result);
        JSONObject object = JSONUtil.parseObj(result);
        String ticket = (String)object.get("ticket");
        return ticket;
    }

    public Map<String, Object> getPrivateAccessToken(String code) {
        String appId = configService.selectConfigByKey("weixin.app.id");
        String appSecret = configService.selectConfigByKey("weixin.app.secret");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        url += "?appid=" + appId;
        url += "&secret=" + appSecret;
        url += "&code=" + code;
        url += "&grant_type=authorization_code";
        try {
            String result = HttpUtil.get(url);
            Map object = JSONUtil.toBean(result, Map.class);
            log.info("url:" + url + ";  response:" + JSONUtil.toJsonStr(object));
            String access_token = (String)object.get("access_token");
            if (StringUtils.isNotEmpty(access_token)) {
                return object;
            }
        } catch (Exception e) {
            log.error("获取token失败", e);
        }
        return null;
    }
    public String getOpenIdByCode(String code) {
        Map<String, Object> ret = getPrivateAccessToken(code);
        log.info("获取openId:{}", JSONUtil.toJsonStr(ret));
        if (ret != null && ret.get("errcode") == null) {
            String openId = String.valueOf(ret.get("openid"));
            return openId;
        }
        return null;
    }
}
